package com.ljw.zookeeper;


import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * @Author: lijunwei
 * @Time: 2019/8/10 20:04
 */
public class ServiceRegistryImp implements ServiceRegistry {

    private static final String REGISTRY_ROOT = "/registry";

    private static CuratorFramework client = null;

    static {
        client=CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(3000)
                .connectionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 10))
                .build();
        client.start();
    }

    public void registry(String serviceName, String serviceAdrr) throws Exception {
        String servicePath = REGISTRY_ROOT + "/" + serviceName;
        Stat stat = client.checkExists().forPath(servicePath);
        if (client.checkExists().forPath(servicePath)==null){
            client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(servicePath);
        }
        String addressPath = servicePath+ "/" + serviceAdrr;
        client.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath);
        System.out.println(serviceName+"---服务注册----"+addressPath);
    }


    public static void main(String[] args) throws Exception {
        ServiceRegistryImp serviceRegistryImp = new ServiceRegistryImp();
        serviceRegistryImp.registry("product-service","127.0.0.1:2181");
        System.in.read();
    }

}
